<?php

namespace app\index\controller;

use app\admin\library\Auth;
use app\common\controller\Frontend;
use EasyWeChat\Factory;
use app\admin\model\Admin;
use app\common\controller\Api;
use app\common\library\Upload;
use think\Db;

class Toolposter extends Frontend
{

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $layout = '';
    public $type_img = [
                        1=>['name'=>'1海报.jpg','erweim_wz'=>[535,1036],'erweim_size'=>145],
                        2=>['name'=>'2海报.jpg','erweim_wz'=>[555,1592],'erweim_size'=>170],
                    ];
      
    public $url_img = ROOT_PATH.'public/tool/haibao/';

   /**
     * 公共
     * @author gzy
     * @date   2018年8月12日 09:15:00
     */
    public function _initialize(){
        parent::_initialize();
        $Api = new Api();
        //获取默认值
        $this->config = $Api->getConfig($Api->getDefault('Assistant'));
        $this->config['oauth']['callback'] = "http://oa.fc62.com/index/toolposter/login";
        $this->auth = \app\admin\library\Auth::instance();
        $this->model = new \app\admin\model\tool\Poster;
       
        //退出
        //print_r($this->auth->logout());die; 
        //模拟登陆
      // $this->auth->IndexLogin('GaoZhenYu');
        //判断权限
        //print_r($this->auth->check('see/index'));die;
    }

   
    public function index(){
       $this->auth->logout();
       // 检测是否需要验证登录
       return redirect($this->request->domain().'/index/toolposter/login');
        
    }  
    /**
     * 生成苏回音
     */
    public function generate(){

       if ($this->request->isPost()){
            $params = $this->request->post();
            if ($params) {
                Db::startTrans();
                $result = $this->watermark($params);
                if(!$result){ 
                    Db::rollback();
                    $this->error("操作失败");
                }
                if($result['true']==1){
                    $arr = [];
                    $arr['userid'] = \think\Session::get('admin')['userid'];
                    $arr['type'] = $params['type'];
                    $arr['erweima_img'] = $params['erweima'];
                    $arr['generate_img'] = $result['data'];
                    $info = $this->model->allowField(true)->save($arr);
                    if($info){
                        Db::commit();
                        $this->success('操作成功','',$result['data']);
                    }else{
                        Db::rollback();
                    }
                }else{
                    $this->error("操作失败");
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
       } 
       return $this->view->fetch();
 
    }    
    /**
     * 生成苏回音
     */
    public function watermark($arr = []){
        if(!$arr['type']) return ['true'=>0,'msg'=>'参数错误'];
        $filename = $this->url_img.$this->type_img[$arr['type']]['name'];
        //设置路径目录信息
        $url = ROOT_PATH . 'public/uploads/tool/'.date("Ymd").'/hb'.$arr['type'].'/'.date('YmdHis') . uniqid().'.png';  
        $dir_name = dirname($url);
         //目录不存在就创建
        if(!file_exists($dir_name)) {
            //iconv防止中文名乱码
           $res = mkdir(iconv("UTF-8", "GBK", $dir_name),0777,true);
        }
        $imglName = "uploads/tool/".date("Ymd")."/hb".$arr['type']."/".date('YmdHis') . uniqid().'.png';
        $no_url  = '/'.$imglName.'';
        //字体url
        $zitiurl = $this->url_img.'simsun.ttf';
         //二维码缩略
        $er_image = \think\Image::open(ROOT_PATH.'/public'.$arr['erweima']);
        $er_image->thumb($this->type_img[$arr['type']]['erweim_size'],$this->type_img[$arr['type']]['erweim_size'],\think\Image::THUMB_CENTER)->save(ROOT_PATH.'/public'.$arr['erweima']);
         $image = \think\Image::open($filename); //要加水印的图片
       
        //二维码位置
        $erweim_wz = $this->type_img[$arr['type']]['erweim_wz'];
        $image->water(ROOT_PATH.'/public'.$arr['erweima'],$erweim_wz)->save($imglName); 
     
        return ['true'=>1,'msg'=>'操作成功','data'=>$no_url];
 
    }
 
    /**
     * 测试
     */
    public function test($arr = []) {
        echo "<textarea></textarea>";
        $peizhi = $this->type_img[1];
        $filename = $this->url_img.$peizhi['name'];
        //设置路径目录信息
        $url = ROOT_PATH . 'public/uploads/tool/'.date("Ymd").'/hb1/'.time().'.png';  
        $dir_name = dirname($url);
         //目录不存在就创建
        if(!file_exists($dir_name)) {
            //iconv防止中文名乱码
           $res = mkdir(iconv("UTF-8", "GBK", $dir_name),0777,true);
        }
        $imglName = "uploads/tool/".date("Ymd")."/hb1/".time().'.png';
        $no_url  = ''.request()->domain().'/'.$imglName.'';
        // $wenke=array(1145,460);
         $image = \think\Image::open($filename); //要加水印的图片
        // $image->text('一年级',$this->url_img.'simsun.ttf',45,'#060610',$wenke)->save($imglName);
        //  // $wz=array(310,1830);
        //  // $image->text('    讲座时间：2月20日、21日、22日、23日每晚8~9点。讲座时间：2月20日',$this->url_img.'simsun.ttf',40,'#222125',$wz,0,0,1905)->save($imglName);
        //  //   $wz=array(310,1895);
        //  // $image->text('    2月20日，语文：北京五中徐春老师主讲；2月21日，英语：北京171中学秦建鹏老师主讲；2月22日，数学：北京五中熊丹老师主讲；冲刺阶段对策讲座：全科资讯梁星老师主讲（2月23日）全科资讯梁星老师主讲（2月全科资讯梁星老',$this->url_img.'simsun.ttf',40,'#222125',$wz,0,0,1905)->save($imglName);
        // $wz=$peizhi['date_wz'];
        // $image->text('2月10日前',$this->url_img.'simsun.ttf',40,'#17161c',$wz)->save($imglName);
         $wz=$peizhi['erweim_wz'];
         //二维码缩略
         $er_image = \think\Image::open($this->url_img.'er.jpg');
        // 按照原图的比例生成一个最大为150*150的缩略图并保存为thumb.png
         $er_image->thumb(145,145,\think\Image::THUMB_CENTER)->save($this->url_img.'er.jpg');
        $image->water($this->url_img.'er.jpg',$wz)->save($imglName); 
        echo'<img src="'.$no_url.'" height="900">';die;
    }
    public function login(){
        $app = Factory::work($this->config);
        $token = $app->access_token->getToken();//获取企业微信token
        $code = $this->request->request('code');
        $url = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token={$token['access_token']}&code={$code}";
        $user = \fast\Http::get($url);
        if(!empty($user)) $user = json_decode($user,true);
        
        if($user['errcode'] == 0){
            if(isset($user['UserId'])){
                if(!$this->auth->IndexLogin($user['UserId'])){
                    $this->error(__('您的账户不存在，请联系管理员'));
                }else{
                    //print_r(\think\Session::get('admin')['userid']);die;
                    return redirect($this->request->domain().'/index/Toolposter/generate');
                }
            }
        }else{
            return redirect($this->request->domain().'/index/Toolposter/oauth');
        }
    }
   public function oauth(){
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$this->config['corp_id']."&redirect_uri=".$this->config['oauth']['callback']."&response_type=code&scope=".$this->config['oauth']['scopes']."&agentid=".$this->config['agent_id']."&state=STATE#wechat_redirect";
        return redirect($url);
    }
     public function upload(){
        //是否有图片上传
        if ($this->request->request('file')) {
            $upload = new Upload();
            $upload->path(ROOT_PATH.'public/uploads/tool/hb/erweima');//上传 发货凭证
            $file = $upload->upbase($this->request->request('file'),'/uploads/tool/hb/erweima/');
            if($file){
                 $this->success('操作成功','',$file);
            }else{
                 $this->error($upload->error());
            }
        }
    }
  

}
